package com.campus.food.controller;

import com.campus.food.model.entity.Cart;
import com.campus.food.service.CartService;
import com.campus.food.util.Result;
import com.campus.food.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 购物车控制器
 * 处理购物车相关的HTTP请求
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-05-29
 */
@RestController
@RequestMapping("/api/cart")
@Validated
public class CartController {
    
    @Autowired
    private CartService cartService;
    
    /**
     * 添加商品到购物车
     * POST /api/cart/add
     */
    @PostMapping("/add")
    public Result<Cart> addToCart(@Valid @RequestBody Cart cart) {
        try {
            Cart savedCart = cartService.addToCart(cart);
            return Result.success("商品已添加到购物车", savedCart);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("添加到购物车失败，请稍后重试");
        }
    }
    
    /**
     * 根据ID获取购物车项
     * GET /api/cart/{id}
     */
    @GetMapping("/{id}")
    public Result<Cart> getCartById(@PathVariable @NotNull Long id) {
        try {
            Cart cart = cartService.getCartById(id);
            return Result.success(cart);
        } catch (BusinessException e) {
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取购物车信息失败");
        }
    }
    
    /**
     * 根据用户ID和菜品ID获取购物车项
     * GET /api/cart/user/{userId}/food/{foodId}
     */
    @GetMapping("/user/{userId}/food/{foodId}")
    public Result<Cart> getCartByUserIdAndFoodId(@PathVariable @NotNull Long userId,
                                                @PathVariable @NotNull Long foodId) {
        try {
            Cart cart = cartService.getCartByUserIdAndFoodId(userId, foodId);
            if (cart == null) {
                return Result.notFound("购物车中没有此商品");
            }
            return Result.success(cart);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取购物车信息失败");
        }
    }
    
    /**
     * 更新购物车商品数量
     * PUT /api/cart/{id}/quantity
     */
    @PutMapping("/{id}/quantity")
    public Result<String> updateCartQuantity(@PathVariable @NotNull Long id,
                                           @RequestParam @NotNull Integer quantity,
                                           @RequestParam @NotNull Long userId) {
        try {
            boolean success = cartService.updateCartQuantity(id, quantity, userId);
            if (success) {
                return Result.success("数量更新成功");
            } else {
                return Result.error("数量更新失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新购物车数量失败");
        }
    }
    
    /**
     * 删除购物车项
     * DELETE /api/cart/{id}
     */
    @DeleteMapping("/{id}")
    public Result<String> removeFromCart(@PathVariable @NotNull Long id,
                                       @RequestParam @NotNull Long userId) {
        try {
            boolean success = cartService.removeFromCart(id, userId);
            if (success) {
                return Result.success("商品已从购物车移除");
            } else {
                return Result.error("移除失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("删除购物车项失败");
        }
    }
    
    /**
     * 获取用户购物车列表
     * GET /api/cart/user/{userId}
     */
    @GetMapping("/user/{userId}")
    public Result<List<Cart>> getCartByUserId(@PathVariable @NotNull Long userId) {
        try {
            List<Cart> cartList = cartService.getCartByUserId(userId);
            return Result.success(cartList);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取购物车列表失败");
        }
    }
    
    /**
     * 根据用户ID和商家ID获取购物车列表
     * GET /api/cart/user/{userId}/merchant/{merchantId}
     */
    @GetMapping("/user/{userId}/merchant/{merchantId}")
    public Result<List<Cart>> getCartByUserIdAndMerchantId(@PathVariable @NotNull Long userId,
                                                          @PathVariable @NotNull Long merchantId) {
        try {
            List<Cart> cartList = cartService.getCartByUserIdAndMerchantId(userId, merchantId);
            return Result.success(cartList);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取购物车列表失败");
        }
    }
    
    /**
     * 清空用户购物车
     * DELETE /api/cart/clear/{userId}
     */
    @DeleteMapping("/clear/{userId}")
    public Result<String> clearCart(@PathVariable @NotNull Long userId) {
        try {
            boolean success = cartService.clearCart(userId);
            if (success) {
                return Result.success("购物车已清空");
            } else {
                return Result.error("清空购物车失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("清空购物车失败");
        }
    }
    
    /**
     * 清空用户在指定商家的购物车
     * DELETE /api/cart/clear/{userId}/merchant/{merchantId}
     */
    @DeleteMapping("/clear/{userId}/merchant/{merchantId}")
    public Result<String> clearCartByMerchant(@PathVariable @NotNull Long userId,
                                            @PathVariable @NotNull Long merchantId) {
        try {
            boolean success = cartService.clearCartByMerchant(userId, merchantId);
            if (success) {
                return Result.success("购物车已清空");
            } else {
                return Result.error("清空购物车失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("清空购物车失败");
        }
    }
    
    /**
     * 批量删除购物车项
     * DELETE /api/cart/batch
     */
    @DeleteMapping("/batch")
    public Result<String> removeCartBatch(@RequestParam List<Long> ids,
                                        @RequestParam @NotNull Long userId) {
        try {
            boolean success = cartService.removeCartBatch(ids, userId);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("批量删除购物车项失败");
        }
    }
    
    /**
     * 获取用户购物车商品数量
     * GET /api/cart/count/{userId}
     */
    @GetMapping("/count/{userId}")
    public Result<Long> getCartCount(@PathVariable @NotNull Long userId) {
        try {
            long count = cartService.getCartCount(userId);
            return Result.success(count);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取购物车数量失败");
        }
    }
    
    /**
     * 获取用户在指定商家的购物车商品数量
     * GET /api/cart/count/{userId}/merchant/{merchantId}
     */
    @GetMapping("/count/{userId}/merchant/{merchantId}")
    public Result<Long> getCartCountByMerchant(@PathVariable @NotNull Long userId,
                                             @PathVariable @NotNull Long merchantId) {
        try {
            long count = cartService.getCartCountByMerchant(userId, merchantId);
            return Result.success(count);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取购物车数量失败");
        }
    }
    
    /**
     * 获取所有购物车列表（管理员专用）
     * GET /api/cart/admin
     */
    @GetMapping("/admin")
    public Result<List<Cart>> getAllCarts(@RequestParam(defaultValue = "1") int page,
                                        @RequestParam(defaultValue = "10") int size,
                                        @RequestParam(required = false) Long userId,
                                        @RequestParam(required = false) Long merchantId) {
        try {
            List<Cart> carts = cartService.getAllCarts(page, size, userId, merchantId);
            return Result.success(carts);
        } catch (Exception e) {
            return Result.error("获取购物车列表失败");
        }
    }
    
    /**
     * 获取用户购物车详情信息（包含菜品名称、图片等详细信息）
     * GET /api/cart/detail/{userId}
     */
    @GetMapping("/detail/{userId}")
    public Result<List<Map<String, Object>>> getUserCartDetail(@PathVariable @NotNull Long userId) {
        try {
            // 获取用户购物车列表并附加详细信息
            List<Map<String, Object>> cartDetailList = cartService.getUserCartDetail(userId);
            
            if (cartDetailList.isEmpty()) {
                return Result.success("购物车为空", cartDetailList);
            }
            
            return Result.success(cartDetailList);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取购物车详情失败");
        }
    }
} 